package biz.datalk.industrialland.common.util;

import biz.datalk.industrialland.common.exception.ServiceException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

/**
 * @author tarofang@163.com
 * @date 2024-01-17
 */
public class RequestUtil {

    public static String getRequestBody(HttpServletRequest request) {
        try {
            return IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException ioEx) {
            throw new ServiceException("获取请求体失败");
        }
    }

    public static Map<String, String> getUrlParams(HttpServletRequest request) {
        Map<String, String> resMap = new HashMap<>();

        Enumeration<String> parameterNames = request.getParameterNames();
        String pName, val;
        while (parameterNames.hasMoreElements()) {
            pName = parameterNames.nextElement();
            val = request.getParameter(pName);
            resMap.put(pName, val);
        }

        return resMap;
    }

    public static IdentityHashMap<String, String> getHeaders(HttpServletRequest request) {
        String hName, val;
        IdentityHashMap<String, String> headerMaps = new IdentityHashMap<>();
        for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
            hName = headerNames.nextElement();
            for (Enumeration<String> headerValues = request.getHeaders(hName); headerValues.hasMoreElements();) {
                val = headerValues.nextElement();
                headerMaps.put(new String(hName.getBytes(), StandardCharsets.UTF_8), val);
            }
        }
        return headerMaps;
    }

    private void printHeader(HttpServletRequest request, Logger log) {
        String uri = request.getRequestURI();
        String hName, val;
        for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
            hName = headerNames.nextElement();
            for (Enumeration<String> headerValues = request.getHeaders(hName); headerValues.hasMoreElements();) {
                val = headerValues.nextElement();
                log.debug("uri:{} | {} |--------| {}", uri, hName, val);
            }
        }
    }



}
